'use strict';
let fs=require('fs');
let path=require('path');
let router=require('koa-router')();
function searchforEach(defaultDir){
    let files=fs.readdirSync(defaultDir);
    let result=files.filter((fileName)=>{
        return fileName.endsWith('js')&&fileName!='index.js';
    })
    return result;
}
function registerforEach(files){
    files.forEach(item=>{
        let tmpPath=path.join(__dirname,item);
        let routerObj=require(tmpPath);
        for(let key in routerObj){
            let type=routerObj[key][0];
            let fn=routerObj[key][1];
            if(type==='get'){
                router.get(key,fn);
            }else if(type==='post'){
                router.post(key,fn);
            }else if(type==='put'){
                router.put(key,fn);
            }else if(type==='delete'){
                router.delete(key,fn);
            }
        }
    })
}
module.exports=function(dir){
    let resultFilePath=dir||__dirname;
    let files=searchforEach(resultFilePath);
    registerforEach(files);
    return router.routes();
}